package cn.tedu.tmall.admin.mall.filter;

import cn.tedu.tmall.admin.mall.dao.persist.cache.IUserCacheRepository;
import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmall.common.pojo.po.UserStatePO;
import cn.tedu.tmall.common.web.JsonResult;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {
    @Value("${tmall.jwt.secret-key}")
    private String secretKey;
    @Autowired
    private IUserCacheRepository cacheRepository;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if (requestURI.endsWith(".css") || requestURI.endsWith(".js")) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }
        System.out.println(request.getRequestURI());
        System.out.println("JwtAuthorizationFilter.doFilterInternal()");
        //接收jwt
        String jwt = request.getHeader("Authorization");
        System.out.println("客户端携带的JWT："+jwt);

        //检查jwt的基本有效性
        if(!StringUtils.hasText(jwt)){
            filterChain.doFilter(request,response);
            return;
        }

        //在解析jwt之前将存入session中的authentication认证信息清除，因为session具备时效性，如果此次请求不携带jwt，
        //Security也能从session中读取到之前请求存入的认证信息，从而通过本次请求的认证；
        //缺点：session中的认证信息会存储到下次的请求才会被清除，这样会造成资源的浪费；
        // 更好的方法是在Security配置类中配置不使用session；
        //SecurityContextHolder.clearContext();

        //解析jwt
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch (ExpiredJwtException e) {
            String message = "您的登录信息已经过期，请重新登录！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_EXPIRED, message);
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(jsonResult));
            writer.close();
            return;
        } catch (SignatureException e) {
            String message = "非法访问！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(jsonResult));
            writer.close();
            return;
        } catch (MalformedJwtException e) {
            String message = "非法访问！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_MALFORMED, message);
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(jsonResult));
            writer.close();
            return;
        } catch (Throwable e) {
            String message = "服务器忙，请稍后再试！【开发阶段：同学们，当你看到这句话时，你应该通过服务器端的控制台了解本次出现异常的原因，并添加针对处理此异常的方法】";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERROR_UNKNOWN, message);
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(jsonResult));
            writer.close();
            return;
        }

        Long id = claims.get("id", Long.class);
        String username = claims.get("username", String.class);
        String jwtRemoteAddr = claims.get("remoteAddr", String.class);
        String jwtUserAgent = claims.get("userAgent", String.class);

        String remoteAddr = request.getRemoteAddr();
        String userAgent = request.getHeader("user-Agent");

        if(!jwtRemoteAddr.equals(remoteAddr) && !jwtUserAgent.equals(userAgent)){
            filterChain.doFilter(request,response);
            return;
        }

        // 从redis中获取用户信息
        UserStatePO userState = cacheRepository.getUserState(id);

        // 判断用户账号状态
        // 注意：在设计“禁用账号”时，需要删除此账号在Redis中对应的数据
        if (userState == null) {
            String message = "您的登录信息已经过期！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERROR_UNAUTHORIZED, message);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(jsonResult));
            writer.close();
            return;
        }

        if (userState.getEnable() == 0) {
            String message = "您的账号状态已经被禁用！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERROR_UNAUTHORIZED_DISABLED, message);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(jsonResult));
            writer.close();
            return;
        }

        //当事人信息
        CurrentPrincipal principal = new CurrentPrincipal();
        principal.setId(id);
        principal.setUsername(username);

        //权限
        String authoritesToString = userState.getAuthoritesToString();
        List<SimpleGrantedAuthority> authorities =
                JSON.parseArray(authoritesToString, SimpleGrantedAuthority.class);

        //将用户的认证信息存入SecurityContent中
        Authentication authentication = new UsernamePasswordAuthenticationToken(principal,null,authorities);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);

        filterChain.doFilter(request,response);
    }
}
